/****************************************************
 * The SNIFFER Usability Library
 * Local IP address capture
 * -----------------------------
 *
 * C. Nunez 	(cnunez@stevens.edu)
 * W. Best		(wbest@stevens.edu)
 * K. Fuhrman 	(ktfuhrman@gmail.com)
 * M. DiAmore 	(mdiamore@gmail.com)
 *
 * Date Created:	20 May, 2010
 *
 * Description
 * -----------
 * This library gets host IP address.
 ****************************************************/

#include "print_localhost.h"

int main() {
  if(!setup_wsa()) return 2;
  print_localhost();
  cleanup_wsa();
  cin.get();
}

void print_localhost() {
  cout << "Hostname: " << getip() << "\n";
}

BOOL setup_wsa() {
  WSAData wsaData;
  if(WSAStartup(MAKEWORD(1, 1), &wsaData))
    return 0;
  return 1;
}

void cleanup_wsa() {
  WSACleanup();
}

const char* getip() {
  char host[100];
  if(gethostname(host, sizeof(host)) == SOCKET_ERROR)
    report_sockerr();
  string host_s(host);
  hostent* he_ptr = gethostbyname(host);
  if(!he_ptr)
    report_sockerr();
  in_addr addr_s;
  memcpy(&addr_s, he_ptr->h_addr_list[0], sizeof(addr_s));
  string addr_str(inet_ntoa(addr_s));
  addr_str += "/" + host_s;
  return addr_str.c_str();
}

void report_sockerr() {
  cerr << "An error occurred: " << WSAGetLastError() << "\n";
  exit(2);
}